import { getCurrentInstance, PropType, defineComponent, ComponentInternalInstance } from "vue";
import { SearchItem } from "./interface";
import "./search-form.scss";
export default defineComponent({
	props: {
		collapsed: Boolean,
		searchItems: {
			type: Array as PropType<SearchItem[]>,
			default() {
				return [];
			}
		},
		search: {
			type: Object,
			default() {
				return {};
			}
		},
		searchCols: {
			type: Number,
			default() {
				return 4;
			}
		}
	},
	emits: ["featch", "update:collapsed"],
	setup(props, { slots, emit }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const resetSearchParam = () => {
			for (let key in props.search) {
				props.search[key] = null;
			}
			emit("featch");
		};
		return () => {
			return (
				<div>
					{slots.default?.() || (
						<el-form
							class="search-form grid grid-cols-4 gap-4"
							onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? emit("featch") : null)}
						>
							{props.searchItems.map((item, i) => {
								return i < props.searchCols || !props.collapsed ? (
									<el-form-item class="search-item" label={item.label}>
										{slots[item.key] ? (slots[item.key] as Function)(item) : <el-input v-model={props.search[item.key]} />}
									</el-form-item>
								) : null;
							})}
							<el-form-item class="search-item">
								<el-button type="primary" class="iconfont iconsearch" onClick={() => emit("featch")}>
									{proxy?.$t("common.btn.search")}
								</el-button>
								<el-button class="iconfont iconsearch" onClick={resetSearchParam}>
									{proxy?.$t("common.btn.reset")}
								</el-button>
								{props.searchItems.length > props.searchCols ? (
									<el-button
										v-if="showCollapse"
										type="primary"
										link
										class="search-isOpen"
										onClick={emit("update:collapsed", !props.collapsed)}
									>
										{props.collapsed ? "展开" : "合并"}
										<span class={props.collapsed ? "iconfont iconchevron-down" : "iconfont iconchevron-up"}></span>
									</el-button>
								) : null}
							</el-form-item>
						</el-form>
					)}
				</div>
			);
		};
	}
});
